// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async event => {
  const { _id, audit = 0, order = 'desc', koi, limit = 50, skip = 0 } = event

  const { list } = await db
    .collection('promotion')
    .aggregate()
    .match({
      audit: { status: audit },
      koi,
    })
    .limit(limit)
    .skip(skip)
    .lookup({
      from: 'store',
      localField: '_openid',
      foreignField: '_openid',
      as: 'store',
    })
    .replaceRoot({
      newRoot: $.mergeObjects([
        '$$ROOT',
        {
          store: $.arrayElemAt(['$store', 0]),
        },
      ]),
    })
    .project({
      _openid: 0,
      store: {
        _openid: 0,
        owner: 0,
        account: 0,
        audit: 0,
      },
    })
    .sort({
      createAt: order === 'desc' ? -1 : 1,
    })
    .end()

  return list
}
